import numpy as np
import matplotlib.pyplot as plt

x_data = [1.0, 2.0, 3.0]
y_data = [2.0, 4.0, 6.0]

w = 1.0

def forward(x):
    return x * w

def loss(x, y):
    '''

    :param x:
    :param y:
    :return:
    '''
    y_pred = forward(x)
    return (y_pred - y) ** 2

def gradient(x, y):
    '''
    对于loss的函数进行求导数计算 偏loss/偏w
    :param x:
    :param y:
    :return:
    '''
    y_pred = forward(x)
    return 2 * x * (y_pred - y)


epoch_list = []
loss_list = []

print("Predict before training:",4, forward(4))
print(x_data)
print(y_data)
for epoch in range(100):
    for x, y in zip(x_data, y_data):
        grad = gradient(x, y)
        w = w - 0.01 * grad
        print("\tgrad: ", x, y, grad)
        l = loss(x, y)
        epoch_list.append(epoch)
        loss_list.append(l)
    print("progress:", epoch, w, l, grad)

plt.plot(epoch_list, loss_list)
plt.xlabel('epoch')
plt.ylabel('Loss')
plt.show()




